<?php
/**
 * Profile Model for Congregation Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_4
 * @license		GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

/**
 * Profile Model
 *
 * @package    Congregation
 * @subpackage Components
 */
class CongregationModelProfile extends CongregationModel
{
	/**
	 * Constructor that retrieves the ID from the request
	 *
	 * @access	public
	 * @return	void
	 */
	 
	 protected $_c_id;
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->_c_id = JRequest::getCmd('c_id');

	}

	/**
	 * Method to set the profile identifier
	 *
	 * @access	public
	 * @param	int Sharing identifier
	 * @return	void
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
		$this->_datalist = null;
		$this->_provincelist = null;
	}

	/**
	 * Method to get a sharing
	 * @return object with data
	 */
	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT c.* FROM #__congregation_profile AS c '.
					' WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
			
			if($this->_data)
			{
				$query = "SELECT t.*, c.c_name FROM #__congregation_profile_paths t LEFT JOIN #__congregation_casa c ON t.t_cid=c.c_id WHERE t_username = '{$this->_data->username}' ORDER BY t.t_date DESC ";
				$this->_db->setQuery( $query );
				$this->_data->paths = $this->_db->loadObjectList();
				
				$query = "SELECT * FROM #__congregation_profile_photos WHERE username = '{$this->_data->username}' ORDER BY id DESC LIMIT 1";
				$this->_db->setQuery( $query );
				$this->_data->photo = $this->_db->loadObject();
				
			}
		}
		if (!$this->_data) {
			$this->_data = & JTable::getInstance('profile', 'Table');
		}
		
		
		return $this->_data;
	}

	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store()
	{	
		$row =& $this->getTable();

		$data = JRequest::get( 'post' );
		

		$data['bdate'] = $data['b_year']['0'] . '-' . $data['b_month']['0'] . '-' .$data['b_day']['0'];
		$data['edate'] = $data['b_year']['1'] . '-' . $data['b_month']['1'] . '-' .$data['b_day']['1'];
		$data['ndate'] = $data['b_year']['2'] . '-' . $data['b_month']['2'] . '-' .$data['b_day']['2'];
		$data['vdate'] = $data['b_year']['3'] . '-' . $data['b_month']['3'] . '-' .$data['b_day']['3'];
		$data['fdate'] = $data['b_year']['4'] . '-' . $data['b_month']['4'] . '-' .$data['b_day']['4'];
		$data['odate'] = $data['b_year']['5'] . '-' . $data['b_month']['5'] . '-' .$data['b_day']['5'];
		$data['ddate'] = $data['b_year']['6'] . '-' . $data['b_month']['6'] . '-' .$data['b_day']['6'];
		
		$data['bplace'] = $data['b_place']['0'];
		$data['eplace'] = $data['b_place']['1'];
		$data['nplace'] = $data['b_place']['2'];
		$data['vplace'] = $data['b_place']['3'];
		$data['fplace'] = $data['b_place']['4'];
		$data['oplace'] = $data['b_place']['5'];
		$data['dplace'] = $data['b_place']['6'];
		
		//about paths
		
		$paths = JRequest::getVar('path');

		if(!is_null($paths))
		{
			//delete all charges first
			$query = "DELETE FROM #__congregation_profile_paths WHERE t_username = '{$data['username']}'";

			$this->_db->setQuery($query);
			$this->_db->query();
			//add all submitted charges

			for($i = 0; $i < count($paths); $i++)
			{
				$t_current = JRequest::getVar('t_current');
				$i_t_current = 0;
				if($t_current == $i)
				{
					$i_t_current = 1;
				}
				if(($paths[$i]['t_year']) && ($paths[$i]['t_house']) && empty($paths[$i]['delete']))
				{
				
					if(empty($paths[$i]['t_day'])) $paths[$i]['t_day'] = "1";
					if(empty($paths[$i]['t_month'])) $paths[$i]['t_month'] = "1";
					$query = "INSERT INTO #__congregation_profile_paths (t_date, t_cid, t_charge, t_current, t_username) VALUES ('" . $paths[$i]['t_year'] . "-" . $paths[$i]['t_month'] . "-" . $paths[$i]['t_day'] . "', '" . $this->_db->getEscaped($paths[$i]['t_house']) . "', '" . $this->_db->getEscaped($paths[$i]['t_charge']) . "', '" . $i_t_current . "', '{$data['username']}')";
					$this->_db->setQuery($query);
					$this->_db->query();
				}
				
				
			}
		}
		

		//about photo?
	

	
        //Retrieve file details from uploaded file, sent from upload form
        $file = JRequest::getVar('photo', null, 'files', 'array'); 
        // Retorna: Array ( [name] => mod_simpleupload_1.2.1.zip [type] => application/zip 
        // [tmp_name] => /tmp/phpo3VG9F [error] => 0 [size] => 4463 ) 
		
		$max = '1000000';
		$dest_dir = JPATH_ROOT . DS . 'media' . DS . 'congregation'. DS . 'profiles' . DS . 'originals';
		$thumb_dir = JPATH_ROOT . DS . 'media' . DS . 'congregation'. DS . 'profiles' . DS . 'thumbnails';
		$file_type = 'image/jpeg';
		$image_width = 150;
		$image_height= 150;
		
		$remove_photo = JRequest::getVar('remove_photo', null);
		if(!is_null($remove_photo))
		{
			$query = "DELETE FROM #__congregation_profile_photos WHERE username='{$data['username']}' ORDER BY id DESC LIMIT 1";
			$this->_db->setQuery($query);
			$this->_db->query();
		}elseif(!empty($file) && $file['name'] != ''){ 
				jimport('joomla.filesystem.file');
                //Clean up filename to get rid of strange characters like spaces etc
                $filename = uniqid('') . '_' . JFile::makeSafe($file['name']);
 
                if($file['size'] > $max) $msg = JText::_('Accept only files under').' '.$max;
                //Set up the source and destination of the file
 
                $src = $file['tmp_name'];
                $dest = $dest_dir . DS . $filename;
 
                //First check if the file has the right extension, we need jpg only
                if ($file['type'] == $file_type || $file_type == '*') { 
                   if ( JFile::upload($src, $dest) ) {
 
						//create thumbnail
						require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_congregation'.DS.'helpers'.DS.'congregationhelper.php');
						$image = CongregationHelper::CroppedThumbnail($dest, $image_width, $image_height);
						imagejpeg($image, $thumb_dir . DS . $filename);
						imagedestroy($image);
						
                       //Redirect to a page of your choice
                        $query = "REPLACE INTO #__congregation_profile_photos (username, filename, `date`) VALUES ('{$data['username']}', '{$filename}', '" . date('Y-m-d') . "')";
						$this->_db->setQuery($query);
						$this->_db->query();
						
                   } else {
                          //Redirect and throw an error message
						$this->setError(JText::_('There was an error during image upload'));
						return false;
                   }
                } else {
                   //Redirect and notify user file is not right extension
						$this->setError(JText::_('Uploaded image invalid'));
						return false;
               }
 
        }


		// Bind the form fields to the sharing table
		if (!$row->bind($data)) {
			
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// if new item, order last in appropriate group
		/*
		if (!$row->id) {

			$row->ordering = $row->getNextOrder();
		}
		*/
		// Make sure the sharing record is valid
		if (!$row->check()) {
			JError::raiseWarning( 500, $this->_db->getError());
			return false;
		}

		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		return true;
	}

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable();

		if (count( $cids )) {
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getError() );
					return false;
				}
			}
		}
		return true;
	}
	
	function &getList()
	{
		if (empty( $this->_datalist ))
		{
			if($this->_c_id)
			{
				$query = " SELECT * FROM #__congregation_profile WHERE id='{$this->_c_id}' ORDER BY ordering ";
			}
			else
			{
				$query = " SELECT * FROM #__congregation_profile ORDER BY ordering ";
			}
			$this->_db->setQuery( $query );
			$this->_datalist = $this->_getList( $query );
		}
		return $this->_datalist;
	}

	function &getFreeUsers()
	{
		$query = "SELECT u.* FROM #__users u LEFT JOIN #__congregation_profile m ON u.username = m.username WHERE m.username IS NULL";
		$this->_db->setQuery( $query );
		return $this->_getList( $query );
	}
	
	function &getHouse()
	{
		$this->_username = JRequest::getWord('username', $this->_username);
		$query = "SELECT c.c_id, c.c_name FROM #__congregation_profile_paths t LEFT JOIN #__congregation_casa c ON t.t_cid=c.c_id WHERE t_username = '{$this->_username}' AND t.t_current = 1 LIMIT 1";
		$this->_db->setQuery( $query );
		$rows = $this->_db->loadObject();
		return $rows;
	}
	


}